import { updateDom } from "../react-dom/render";
import { isType } from "../utils";


class Updater {
    constructor() {
        this.callbacks = [];
        this.pendingState = [];
        this.isPending = false;
    }
    // setState时添加入队
    add(state, callback, componentInstance) {
        this.componentInstance = componentInstance;
        // 入队
        this.pendingState.push(state);
        callback && this.callbacks.push(callback);
        if (!updateQueue.isPatchUpdate) {
            this.forceUpdate(this.componentInstance.getState(this));
        }
    }
    setup() {
        this.forceUpdate(this.componentInstance.getState(this));
        // state合并完成后调用回调函数
        const callbacks = this.callbacks;
        if (callbacks) {
            callbacks.length && callbacks.forEach(fn => fn());
        }
        // 清空数组队列
        this.callbacks.length = 0;
        this.pendingState.length = 0;
    }
    forceUpdate() {
        updateDom(this.componentInstance);
    }
}

const updater = new Updater();

// 更新队列，和事件处理系统关联
export const updateQueue = {
    isPatchUpdate: false,
    updater: updater,
}


export class Component {
    static isClassComp = true;
    constructor(props) {
        this.props = props;
    }
    setState(state, callback) {
        updater.add(state, callback, this);
    }
    getState(updater) {
        const pendingState = updater.pendingState;
        const len = pendingState.length;
        for (let i = 0; i < len; i++) {
            let newState = pendingState[i];
            // 如果state是一个函数
            if (isType(pendingState[i], 'function')) {
                // 执行这个函数，得到新的state, 并且合并
                newState = newState(this.state);
            }
            this.state = {
                ...this.state, ...newState
            }
        }
        return this.state;
    }
}